package com.john.booter.module.option.dao.impl;

import java.util.Arrays;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Repository;

import com.john.booter.domain.entity.Option;
import com.john.booter.module.option.dao.OptionDao;

@Repository
public class OptionDaoImpl implements OptionDao {

	@PersistenceContext
	private EntityManager em;

	@Override
	public void deleteAll() {
		Query query = em.createQuery("delete from Option");
		query.executeUpdate();
	}
	
	@Override
	public void batchMerge(List<Option> options) {
		for (int i = 0; i < options.size(); i++) {
			em.merge(options.get(i));
			if (i % 30 == 0) {
				em.flush();
				em.clear();
			}
		}
	}

	@Override
	public List<Option> findAll() {
		return em.createQuery("from Option t", Option.class).getResultList();
	}

	@Override
	public List<Option> findByParentCode(String code) {
		TypedQuery<Option> query = em.createQuery("from Option t where t.parentCode = ?1", Option.class);
		query.setParameter(1, code);
		return query.getResultList();
	}

	@Override
	public List<Option> findByCodes(String[] codes) {
		TypedQuery<Option> query = em.createQuery("from Option t where t.code in ?1", Option.class);
		query.setParameter(1, Arrays.asList(codes));
		return query.getResultList();
	}

	@Override
	public void deleteByCodes(List<String> codes) {
		if(CollectionUtils.isEmpty(codes)) {
			return;
		}
		Query query = em.createQuery("delete from Option t where t.code in ?1");
		query.setParameter(1, codes);
		query.executeUpdate();
	}

}
